<template>
    <div class="container">
        <el-row>
            <el-card shadow="never">
                <div slot="header">
                    <el-form :inline="true" :model="searchForm" size="small">
                        <el-form-item label="名称" class="el-search-item">
                            <el-input v-model="searchForm.name" placeholder="请输入机构名称检索" clearable></el-input>
                        </el-form-item>
                        <el-form-item label="创建时间" class="el-search-item">
                            <el-date-picker
                                v-model="checkedTime"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                type="daterange"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item class="el-search-item">
                            <el-button type="success" plain icon="el-icon-search" @click="getDataList()">查询</el-button>
                        </el-form-item>
                        <el-form-item class="el-search-item">
                            <el-button v-if='hasPerm("sys:dept:expand")' type="danger" plain icon="el-icon-sort" @click="openExpand">{{expandWord}}</el-button>
                        </el-form-item>
                        <el-form-item class="el-search-item">
                            <el-button v-if='hasPerm("sys:dept:add")' type="primary" plain icon="el-icon-plus" @click="openAdd">新增机构</el-button>
                        </el-form-item>
                    </el-form>
                </div>

                <!--数据表格-->
                <el-table
                    v-if="refreshTable"
                    v-loading="waitLoading"
                    :data="tableData" style="width: 100%;"
                    :height="tableHeight"
                    :default-expand-all="isExpandAll"
                    ref="multipleTable"
                    row-key="id"
                    :tree-props="{children: 'children'}">
                    <el-table-column type="index" label="序号" align="center" width="80"></el-table-column>
                    <el-table-column prop="name" label="名称" align="center"></el-table-column>
                    <el-table-column prop="parentName" label="父节点名称" align="center"></el-table-column>
                    <el-table-column prop="orderNum" label="排序" align="center">
                        <template slot-scope="scope">
                            <el-tag size="small" effect="plain">{{scope.row.orderNum !== null ? scope.row.orderNum : 0}}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="createTime" label="创建时间" align="center"></el-table-column>
                    <el-table-column v-if='hasPerm("sys:dept:update") || hasPerm("sys:dept:del")' label="更多操作" align="center" width="250">
                        <template slot-scope="scope">
                            <el-button v-if='hasPerm("sys:dept:update")' @click="openUpdate(scope.row)" size="mini" type="text" icon="el-icon-edit">编辑</el-button>
                            <el-button v-if='hasPerm("sys:dept:del")' @click="deleteFun(scope.row)" size="mini" type="text" icon="el-icon-delete">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!--新增对话框-->
                <el-drawer
                    :title="dialog.dialogTitle"
                    :visible.sync="dialog.visible"
                    :direction="dialog.direction"
                    :size="size"
                    :before-close="handleClose"
                >
                    <el-row class="drawer-table">
                        <el-col :span="24">
                            <el-form :rules="rules" ref="deptForm" :model="deptForm" size="small" label-width="80px">
                                <el-form-item prop="parentName" label="上级部门">
                                    <el-input @click.native="showAssignDialog(deptForm.pid)" v-model="deptForm.parentName" placeholder="选择上级部门" auto-complete="off"></el-input>
                                </el-form-item>
                                <el-form-item prop="name" label="部门名称">
                                    <el-input v-model="deptForm.name" placeholder="请输入部门名称" auto-complete="off"></el-input>
                                </el-form-item>
                                <el-form-item prop="master" label="负责人">
                                    <el-input v-model="deptForm.master" placeholder="请输入部门负责人" auto-complete="off"></el-input>
                                </el-form-item>
                                <el-form-item prop="email" label="邮箱">
                                    <el-input v-model="deptForm.email" placeholder="请输入部门负责人邮箱" auto-complete="off"></el-input>
                                </el-form-item>
                                <el-form-item prop="phone" label="联系电话">
                                    <el-input v-model="deptForm.phone" placeholder="请输入部门负责人联系电话" auto-complete="off"></el-input>
                                </el-form-item>
                                <el-form-item prop="orderNum" label="显示排序">
                                    <el-input-number v-model="deptForm.orderNum"></el-input-number>
                                </el-form-item>
                            </el-form>
                        </el-col>
                    </el-row>
                    <el-row class="drawer-footer">
                        <el-col :span="24">
                            <el-button @click="dialog.visible = false" size="small">取 消</el-button>
                            <el-button type="primary" @click="submitFun()" :loading="loading.status" size="small">{{loading.status ? loading.SubText : loading.BtnText}}</el-button>
                        </el-col>
                    </el-row>
                </el-drawer>

                <el-dialog title="选择部门" :visible.sync="parentDialogVisible" width="25%" top="5%">
                    <el-tree :data="treeData"
                             :props="treeProps"
                             show-checkbox
                             check-strictly
                             node-key="id"
                             default-expand-all
                             :default-checked-keys="defKeys"
                             ref="treeRef"
                             @check-change="handleNodeClick"
                             empty-text="加载中，请稍后..."
                             style="height: 55vh;overflow: auto;"
                    ></el-tree>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="parentDialogVisible = false" size="small">取 消</el-button>
                        <el-button type="primary" @click="parentDialogVisible = false" size="small">确 定</el-button>
                    </span>
                </el-dialog>
            </el-card>
        </el-row>
    </div>
</template>

<script>
export default {
    data() {
        return {
            // 弹出层大小
            size: '25%',
            // 是否显示树状弹出层
            parentDialogVisible: false,
            // 表格数据
            tableData: [],
            // 表格高度
            tableHeight: 0,
            // 用来存放日期组件所选中的值
            checkedTime: '',
            // 查询参数
            searchForm: {
                name: null,
                startTime: null,
                endTime: null
            },
            // 表单参数
            deptForm: {
                id: null,
                pid: null,
                parentName: null,
                name: null,
                orderNum: null,
                master: null,
                email: null,
                phone: null
            },
            // 分页参数
            total: 0,
            pageNum: 1,
            pageSize: 8,
            // 弹出层
            dialog: {
                flag: 0,
                dialogTitle: "",
                visible: false,
                direction: 'rtl'
            },
            // 按钮提交文字
            loading: {
                status: false,
                BtnText: '确 定',
                SubText: '提交中...'
            },
            // 遮罩层
            waitLoading: true,
            // 是否展开，默认全部展开
            isExpandAll: false,
            // 展开折叠默认文字
            expandWord: '展开',
            // 重新渲染表格状态
            refreshTable: true,
            // 所有部门数据
            treeData: [],
            // 树形控件的属性绑定对象
            treeProps: {
                children: 'children',
                label: 'name'
            },
            // 默认选中的节点id值
            defKeys: [],
            // 表单校验
            rules: {
                name: [{required: true, trigger: "change",  message: "请输入机构名称"}],
                parentName: [{required: true, trigger: "change",  message: "请选择上级机构"}]
            }
        };
    },
    mounted() {
        this.$nextTick(() => {
            this.tableHeight = window.innerHeight - 205;
        });
    },
    created() {
        this.getDataList()
    },
    watch: {
        "checkedTime"(value) {
            this.searchForm.startTime = null
            this.searchForm.endTime = null
            if (value != null) {
                let timeArr = value.toString().split(",")
                timeArr.forEach((item,i) => {
                    if(i === 0) {
                        this.searchForm.startTime = item
                    }else {
                        this.searchForm.endTime = item
                    }
                })
            }
        }
    },
    methods: {
        handleClose(done) {
            this.resetForm()
            done()
        },
        // 表格展开折叠
        openExpand() {
            this.refreshTable = false
            this.isExpandAll = !this.isExpandAll
            if(this.isExpandAll === false) {
                this.expandWord = '展开'
            }else {
                this.expandWord = '折叠'
            }
            this.$nextTick(() => {
                this.refreshTable = true;
            });
        },
        // 展示部门对话框
        showAssignDialog(parentId) {
            this.getTreeData()
            // 默认选中根节点
            this.defKeys = [parentId]
            this.parentDialogVisible = true
        },
        handleSizeChange(val) {
            this.pageSize = val
            this.getDataList()
        },
        handleCurrentChange(val) {
            this.pageNum = val
            this.getDataList()
        },
        // 获取部门列表
        getDataList() {
            this.waitLoading = true
            this.$api.dept.list({
                name: this.searchForm.name,
                startTime: this.searchForm.startTime,
                endTime: this.searchForm.endTime
            }).then(res => {
                if(res.data.code === 2000){
                    this.tableData = res.data.data
                    this.waitLoading = false
                }
            })
        },
        // 获取所有部门信息
        getTreeData() {
            this.$api.dept.listTree(1).then(res => {
                if(res.data.code === 2000){
                    this.treeData = res.data.data
                }
            })
        },
        // 树组件单选实现
        handleNodeClick(data, checked) {
            if(checked === true) {
                if(this.deptForm.id === data.id) {
                    this.$message.warning("注意：禁止相同节点编辑，请选择其它节点")
                    return
                }else {
                    this.deptForm.parentName = data.name
                    this.deptForm.pid = data.id
                }
                this.$refs.treeRef.setCheckedKeys([data.id]);
            } else {
                if (this.deptForm.pid === data.id) {
                    this.$refs.treeRef.setCheckedKeys([data.pid]);
                }
            }
        },
        // 新增按钮操作
        openAdd() {
            this.deptForm.pid = null
            this.dialog.flag = 0
            this.resetForm("deptForm")
            this.dialog.dialogTitle = "新增机构"
            this.dialog.visible = true
        },
        // 更新按钮操作
        openUpdate(row) {
            this.dialog.flag = 1
            this.resetForm("deptForm")
            this.dialog.dialogTitle = "编辑机构"
            this.dialog.visible = true
            this.getById(row.id)
        },
        // 提交数据
        submitFun() {
            this.$refs.deptForm.validate(valid => {
                if(valid){
                    this.loading.status = true
                    this.$api.dept.saveOrUpdate(this.deptForm,this.dialog.flag).then(res => {
                        if (res.data.code === 2000) {
                            this.$message({type: 'success',message: res.data.msg})
                            this.getDataList()
                            this.dialog.visible = false
                            this.loading.status = false
                        }else{
                            this.$message({type: 'error',message: res.data.msg})
                            this.loading.status = false
                            return false
                        }
                    })
                }
            })
        },
        // 删除按钮操作
        deleteFun(row) {
            this.$confirm("确定删除当前机构吗？", "系统提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: 'error'
            }).then(() =>{
                this.$api.dept.remove(row.id).then(res => {
                    if(res.data.code === 2000){
                        this.$message.success(res.data.msg)
                        this.getDataList()
                    }else {
                        this.$message.error(res.data.msg)
                    }
                })
            }).catch(() => {
                this.$message.info("取消删除")
            });
        },
        // 根据id获取数据信息
        getById(id) {
            this.$api.dept.getById(id).then(res => {
                if (res.data.code === 2000) {
                    this.deptForm = res.data.data;
                }
            })
        },
        // 清空表单
        resetForm(formName) {
            if (this.$refs[formName]) {
                this.$refs[formName].resetFields();
            }
        }
    }
};
</script>

<style lang="less" scoped>
.el-search-item {
    margin-bottom: 0;
}
.el-card/deep/.el-card__body {
    padding: 0 10px 20px 10px !important;
}
.el-card/deep/.el-card__header {
    border-bottom: none !important;
}

</style>
